package com.twang.stock.task;

import com.twang.stock.entity.LongHuInfo;
import com.twang.stock.entity.LongHuInfoXiWei;
import com.twang.stock.mapper.LongHuInfoMapper;
import com.twang.stock.mapper.LongHuInfoXiWeiMapper;
import com.twang.stock.service.LongHuBangService;
import com.twang.stock.task.old.BaseTask;
import com.twang.stock.task.old.GaiNianZiJingPaiHangTask;
import com.twang.stock.utils.date.HolidayCopy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 龙虎榜定时任务
 */
@Slf4j
@Component
public class LongHUDataTask  extends BaseTask {

    @Autowired
    private static String url = "http://data.10jqka.com.cn/market/longhu/";

    @Resource
    private LongHuInfoMapper longHuInfoMapper;

    @Resource
    private LongHuBangService longHuBangService;
    @Resource
    private LongHuInfoXiWeiMapper longHuInfoXiWeiMapper;

    @Scheduled(cron = "0 0 18 * * ?")
    public void exceuteToDayLongHuData() throws Exception {
        if (!isWork()) {
            return;
        }
        getTodayLongHuDataList();
        //
        try {
            LongHuInfo param = new LongHuInfo();
            List<LongHuInfo> result = longHuBangService.query(param);
            result.forEach(item -> {
                try {
                    getLongHuBangInfo(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            log.error("CalculationController.count exception={}", e);
        }
    }
    public void getTodayLongHuDataList() throws Exception {
        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        // 发送请求，并执行
        String htmlForStock = GaiNianZiJingPaiHangTask.getHtmlStrByUrl(url, httpClient, GaiNianZiJingPaiHangTask.COOKIE, GaiNianZiJingPaiHangTask.USER_AGENT);
        // 网页内容解析
        log.info("该网页存在,正在解析:{}", htmlForStock);
        Document doc = Jsoup.parse(htmlForStock);
        // 第一个数组：title：代码、名称、现价、涨跌幅、成交金额、净买入额
        Elements listTrs = doc.select("table[class=m-table]").get(1).select("tr");
        //   doc
        for (int j = 1; j < listTrs.size(); j++) {
            try{
                Elements tds = listTrs.get(j).select("td");
                LongHuInfo longHuInfo = new LongHuInfo();
                longHuInfo.setStockCode(tds.get(1).text());
                longHuInfo.setStockName(tds.get(2).text());
                longHuInfo.setLinkUrl(tds.get(2).select("a").first().attr("href"));
                longHuInfo.setPrice(StringUtils.isEmpty(tds.get(3).text())? BigDecimal.ZERO :replaceUnit(tds.get(3).text()));
                longHuInfo.setZdf(StringUtils.isEmpty(tds.get(4).text())? BigDecimal.ZERO :replaceUnit(tds.get(4).text()));
                longHuInfo.setZcjje(StringUtils.isEmpty(tds.get(5).text())? BigDecimal.ZERO :replaceUnit(tds.get(5).text()));
                longHuInfo.setJmre(StringUtils.isEmpty(tds.get(6).text())? BigDecimal.ZERO :replaceUnit(tds.get(6).text()));
                longHuInfo.setDate(HolidayCopy.getRealToday());
                LongHuInfo param = new LongHuInfo();
                param.setStockCode(longHuInfo.getStockCode());
                param.setDate(longHuInfo.getDate());
                LongHuInfo record = longHuInfoMapper.selectOne(param);
                if(longHuInfo.getStockName().contains("退") || longHuInfo.getStockName().contains("B") ||
                        longHuInfo.getStockName().contains("*ST") || longHuInfo.getStockName().contains("ST") ||
                        longHuInfo.getStockName().contains("*")||
                        longHuInfo.getStockCode().startsWith("8")||
                        longHuInfo.getStockCode().startsWith("4") ||
                        longHuInfo.getStockCode().startsWith("2")  ){
                        continue;
                }else {
                    if (null != record) {
                        longHuInfo.setId(record.getId());
                        BeanUtils.copyProperties(longHuInfo, record);
                        longHuInfoMapper.updateByPrimaryKey(record);
                    } else {
                        longHuInfoMapper.insert(longHuInfo);
                    }
                }
            }catch (Exception e){
                log.error(" 龙虎榜 excpetion",e);
            }
        }
    }

    private static BigDecimal replaceUnit(String str) {
        if (str.contains("亿")) {
            //成交额
            return new BigDecimal(str.replace("亿", ""));
        }
        if(str.contains("万")){
            str = str.replace("万", "");
            return new BigDecimal(str).divide(BigDecimal.valueOf(10000), 6, BigDecimal.ROUND_HALF_UP);
        }
        if (str.contains("%")) {
            return new BigDecimal(str.replace("%", ""));
        }
        return BigDecimal.ZERO;
    }

    /**
     *查询龙虎榜详细席位
     */
    public  void getLongHuBangInfo(LongHuInfo longHuInfo) throws Exception {
        Thread.sleep(1000);
        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        // 发送请求，并执行
        String htmlForStock = GaiNianZiJingPaiHangTask.getHtmlStrByUrl("http://data.10jqka.com.cn/market/lhbgg/code/" + longHuInfo.getStockCode() + "/", httpClient, GaiNianZiJingPaiHangTask.COOKIE, GaiNianZiJingPaiHangTask.USER_AGENT);
        // 网页内容解析
        log.info("该网页存在,正在解析:{}", htmlForStock);
        Document doc = Jsoup.parse(htmlForStock);
        // 第一个数组：title：代码、名称、现价、涨跌幅、成交金额、净买入额
        Elements listTrs = doc.select("table[class=m-table m-table-nosort]").select("tr");
        //   doc
        for (int j = 1; j < listTrs.size(); j++) {
            try {
                Elements tds = listTrs.get(j).select("td");
                String date = tds.get(7).select("a").first().attr("date");
                if (!longHuInfo.getDate().equals(date.replace("-", ""))) {
                    continue;
                }
                longHuInfo.setLongHuType(tds.get(1).text());
//                longHuInfoDetail.setPrice(StringUtils.isEmpty(tds.get(2).text())? BigDecimal.ZERO :replaceUnit(tds.get(2).text()));
                longHuInfo.setBuyAmount(StringUtils.isEmpty(tds.get(4).text()) ? BigDecimal.ZERO : replaceUnit(tds.get(4).text()));
                longHuInfo.setSaleAmount(StringUtils.isEmpty(tds.get(5).text()) ? BigDecimal.ZERO : replaceUnit(tds.get(5).text()));
//                longHuInfoDetail.setJmre(StringUtils.isEmpty(tds.get(6).text())? BigDecimal.ZERO :replaceUnit(tds.get(6).text()));
                if (null == (tds.get(7).select("a").first().attr("rid"))) {
                    continue;
                }
                Long rid = Long.valueOf(tds.get(7).select("a").first().attr("rid"));
                /**
                 * 查询席位:http://data.10jqka.com.cn/ifmarket/getnewlh/code/000671/date/2022-03-22/rid/3/
                 */
                String url = "http://data.10jqka.com.cn/ifmarket/getnewlh/code/" + longHuInfo.getStockCode() + "/date/" + date + "/rid/" + rid + "/";
                // 发送请求，并执行
                String detail = GaiNianZiJingPaiHangTask.getHtmlStrByUrl(url, httpClient, GaiNianZiJingPaiHangTask.COOKIE, GaiNianZiJingPaiHangTask.USER_AGENT);
                // 网页内容解析
                log.info("该网页存在,正在解析:{}", detail);
                Document docDetail = Jsoup.parse(detail);
                // 第一个数组：title：代码、名称、现价、涨跌幅、成交金额、净买入额
                Elements details = docDetail.select("table[class=m_table]").select("tr");

                Boolean buyOSale=Boolean.FALSE;
                for (int m = 1; m < details.size(); m++) {
                    Elements listTrsDetail = details.get(m).select("tr").select("td");
                    LongHuInfoXiWei xiWei = new LongHuInfoXiWei();
                    if (listTrsDetail.size() == 1) {
                        if (listTrsDetail.get(0).text().contains("买入")) {
                            longHuInfo.setLhbMrDesc(listTrsDetail.get(0).select("td").text());
                            longHuInfo.setBuyAmount(new BigDecimal(listTrsDetail.get(0).select("strong").get(0).text()));
                            longHuInfo.setMrzb(new BigDecimal(listTrsDetail.get(0).select("strong").get(1).text().replace("%", "")));
                            continue;
                        }
                        if (listTrsDetail.get(0).text().contains("卖出")) {
                            buyOSale=Boolean.TRUE;
                            longHuInfo.setLhbMcDesc(listTrsDetail.get(0).select("td").text());
                            longHuInfo.setSaleAmount(new BigDecimal(listTrsDetail.get(0).select("strong").get(0).text()));
                            longHuInfo.setMczb(new BigDecimal(listTrsDetail.get(0).select("strong").get(1).text().replace("%", "")));
                            continue;
                        }
                        if (listTrsDetail.get(0).text().contains("买卖净差")) {
                            longHuInfo.setJmre(new BigDecimal(listTrsDetail.get(0).select("strong").get(0).text()));
                            continue;
                        }
                    }
                    if(buyOSale){
                        xiWei.setBuyOrSale("sale");
                    }else{
                        xiWei.setBuyOrSale("buy");
                    }
                    xiWei.setLongHuId(longHuInfo.getId());
                    xiWei.setStockCode(longHuInfo.getStockCode());
                    xiWei.setStockName(longHuInfo.getStockName());
                    try{
                        xiWei.setXiWeiRow(Long.valueOf(listTrsDetail.get(0).text()));
                    }catch (Exception e){
                        log.info("{}",e);
                    }
                    xiWei.setYyb(listTrsDetail.get(1).text().replace("/n","").replace("股份有限公司","").replace("证券营业部","").replace(" ",""));
                    xiWei.setMrje(StringUtils.isEmpty(listTrsDetail.get(2).text()) ? BigDecimal.ZERO : new BigDecimal(listTrsDetail.get(2).text()));
                    xiWei.setMrzzcjb(StringUtils.isEmpty(listTrsDetail.get(3).text()) ? BigDecimal.ZERO : new BigDecimal(listTrsDetail.get(3).text().replace("%","")));
                    xiWei.setMcje(StringUtils.isEmpty(listTrsDetail.get(4).text()) ? BigDecimal.ZERO : new BigDecimal(listTrsDetail.get(4).text()));
                    xiWei.setMczcjb(StringUtils.isEmpty(listTrsDetail.get(5).text()) ? BigDecimal.ZERO : new BigDecimal(listTrsDetail.get(5).text().replace("%","")));
                    xiWei.setJe(StringUtils.isEmpty(listTrsDetail.get(6).text()) ? BigDecimal.ZERO : new BigDecimal(listTrsDetail.get(6).text()));
                    xiWei.setUrl(url);
                    xiWei.setDate(date);
                    LongHuInfoXiWei temp = new LongHuInfoXiWei();
                    temp.setDate(xiWei.getDate());
                    temp.setStockCode(xiWei.getStockCode());
                    temp.setXiWeiRow(xiWei.getXiWeiRow());
                    temp.setBuyOrSale(xiWei.getBuyOrSale());
                    longHuInfoXiWeiMapper.delete(temp);
                    longHuInfoXiWeiMapper.insert(xiWei);
//                    longHuInfo.setDetailId(xiWei.getId());
                }
                longHuInfoMapper.updateByPrimaryKey(longHuInfo);
            } catch (Exception e) {
                log.error(" 龙虎榜 excpetion", e);
            }
        }
    }

//    public static void main(String[] args) throws Exception {
//        LongHuInfo longHuInfo=new LongHuInfo();
//        longHuInfo.setStockCode("000671");
//        longHuInfo.setId(Long.valueOf(3607));
//        longHuInfo.setDate("20220322");
//        getLongHuBangInfo(longHuInfo);
//    }


}
